package com.bidevalution.model;

import com.bidevalution.core.Common;
import com.bidevalution.core.enums.PushActionEnum;
import com.bidevalution.core.enums.PushNodeEnum;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.XMLWriter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.io.StringWriter;

/**
 * 推送中標結果的數據格式
 * @author huyiqi
 * @date 2019/11/16
 */
public class PushData {

    private static final Logger log = LoggerFactory.getLogger(PushData.class);

    /**
     * 屬性值
     */
    private static final String ATTR_VALUE_ENCODING = "gb2312";

    /**
     * 屬性名稱
     */
    private static final String ATTR_NAME_TABLENAME = "tableName";
    private static final String ATTR_NAME_KEY = "key";
    private static final String ATTR_NAME_FIELDID = "FieldID";

    private Document document;
    private Element root;
    private Element row;

    public PushData() {
        //初始化xml對象，添加root節點
        document = DocumentHelper.createDocument();
        document.setXMLEncoding(ATTR_VALUE_ENCODING);
        root = document.addElement(PushNodeEnum.ROOT.getNode());
    }

    /**
     * 設置推送xml的頭節點
     * @param tableName 表明
     * @param key 主鍵名
     * @param sendDateStr 推送日期
     * @param actionType 操作方式（增刪改）
     * @return 返回xml的dom對象
     */
    public PushData setHeader(String tableName, String key, String sendDateStr, PushActionEnum actionType) {
        //在root節點下，添加head節點，設置表明和主鍵名兩個屬性
        Element header = root.addElement(PushNodeEnum.HEAD.getNode());
        header.addAttribute(ATTR_NAME_TABLENAME, tableName);
        header.addAttribute(ATTR_NAME_KEY, key);

        //在head節點下，添加sendDate節點
        Element sendDate = header.addElement(PushNodeEnum.SEND_DATE.getNode());
        sendDate.addText(sendDateStr);
        //在head節點下，添加action節點
        Element action = header.addElement(PushNodeEnum.ACTION.getNode());
        action.addText(actionType.getAction());

        //在head後，添加row節點
        row = root.addElement(PushNodeEnum.ROW.getNode());

        return this;
    }

    /**
     * 添加字段
     * @param fieldName 字段名
     * @param fieldValue 字段值
     * @return 返回xml的dom對象
     */
    public PushData addRowField(String fieldName, String fieldValue) {
        Element field = row.addElement(PushNodeEnum.FIELD.getNode());
        field.addAttribute(ATTR_NAME_FIELDID, fieldName);
        field.addText(fieldValue);
        return this;
    }

    @Override
    public String toString() {
        return Common.xmlToString(document, ATTR_VALUE_ENCODING);
    }
}
